<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>14.组件访问-子访问父-parent-root</title>
</head>
<body>
<div id="app">
  <h2>这里是根组件</h2>
  <hr>
  <cpn></cpn>
</div>

<template id="cpn">
  <div>
    <h2>这里是cpn组件</h2>
    <childrencpn></childrencpn>
  </div>
</template>

<template id="childrenCpn">
  <div>
    <h2>这里是childrencpn组件</h2>
    <button @click="parentClick">$parent按钮</button>
    <button @click="rootClick">$root按钮</button>
  </div>
</template>

<script src="../js/vue.js"></script>
<script>

  const cpn = {
    template: '#cpn',
    data(){
      return {
        name: '这是cpn组件的名字'
      }
    },
    methods: {
      cpnClick() {
        console.log('cpnClick');
      }
    },
    components: {
      childrencpn: {
        template: '#childrenCpn',
        methods: {
          parentClick() {
            // 1、$parent：可以使子组件访问父组件（一般开发中我们都尽可能的让子组件独立，所以$parent不常用）
            console.log(this.$parent);
            console.log(this.$parent.name);
            this.$parent.cpnClick();
          },
          rootClick() {
            // 2、$root：可以使子组件无论在第几个层级，都可以访问到根组件（vue实例组件），一般也不是很常用
            console.log(this.$root);
            console.log(this.$root.message);
            this.$root.rootFunction();
          }
        }
      }
    }
  }

  const app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue'
    },
    components: {
      cpn: cpn
    },
    methods: {
      rootFunction() {
        console.log('rootFunction');
      }
    }
  });
</script>
</body>
</html>
